package com.cdy.server.handler;

import com.cdy.common.command.Command;
import com.cdy.common.command.RequestDownloadCommand;
import com.cdy.common.domain.FileEntity;
import com.cdy.common.domain.FileSectionEntity;
import com.cdy.common.response.RequestDownloadResponse;
import com.cdy.store.repository.FileRepository;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;

/**
 * 请求下载的命令处理器
 *
 * Created by 陈东一
 * 2019/10/24 0024 20:03
 */
public class RequestDownloadCommandHandler  implements CommandHandler {
    private final FileRepository fileRepository;
    
    public RequestDownloadCommandHandler(FileRepository fileRepository) {
        this.fileRepository = fileRepository;
    }
    
    @Override
    public void handle(ChannelHandlerContext ctx, Command msg) {
        RequestDownloadCommand downloadCommand = (RequestDownloadCommand) msg;
        RequestDownloadResponse requestDownloadResponse = new RequestDownloadResponse();
        requestDownloadResponse.setComplete(true);
        requestDownloadResponse.setRequestId(downloadCommand.getRequestId());
        
        FileEntity fileEntity = fileRepository.getFileByFileMd5(downloadCommand.getFileMD5());
        if (fileEntity == null || !fileEntity.getComplete()) {
            requestDownloadResponse.setComplete(false);
            write(ctx, requestDownloadResponse);
            return;
        }
        
        List<FileSectionEntity> fileSectionEntities = fileRepository.listTaskByFileId(fileEntity.getId());
        requestDownloadResponse.setFileEntity(fileEntity);
        requestDownloadResponse.setList(fileSectionEntities);
        write(ctx, requestDownloadResponse);
        
    }
}
